<script setup lang="ts">
import { ref , reactive , toRefs, watch } from 'vue';
import { getMenuSelect , add , update } from '@/api/system/menu';
import { notify } from '@/utils/element';

//定义自定义事件
const emit = defineEmits(['refresh']);

const formRef = ref();

const initData = {menuType: 'C', isLink: false, orderNum: 1,isFrame: '1',isHidden: '0', isCache: '0', meta: {isBreadcrumd: true}}

const state = reactive({
    title: '新增',      //新增 || 编辑
    type: 'add' as FormType,
    visible: false,
    loading: false,
    menuList: [],
    formData: {
        meta: {},
    } as SysMenuType,
})

const { title, type , visible , loading , menuList , formData } = {...toRefs(state)};

defineExpose({
    open,
});

function open(type: FormType, title: string, data= {} as any) {
    state.type = type;
    state.title = title;
    //合并初始数据，深度拷贝，不然会影响原数据
    state.formData = JSON.parse(JSON.stringify({ ...initData, ...data }));
    state.visible = true;
    loadMenuSelect();
}

async function  loadMenuSelect() {
    try {
        state.loading = true;
        const { data } = await getMenuSelect();
        state.menuList = data;
    } catch (error) {
    } finally {
        state.loading = false;
    }
}

function close() {
    if(state.loading) return;
    formRef.value?.resetFields();
    state.visible = false;
}

function submitForm() {
    formRef.value?.validate((valid: boolean) => {
        if(!valid) return;
        //校验通过
        if(state.formData.menuType == 'F') {
            state.formData.path = '';
            state.formData.pathName = '';
            state.formData.redirect = '';
            state.formData.component = '';
            state.formData.isLink = false;
            state.formData.icon = '';
            state.formData.linkTo = '';
            state.formData.isHidden = '0';
            state.formData.isCache = '0';
            state.formData.meta.isBreadcrumd = false;
        }
        //调用接口，提交数据
        submitData();
    });
}

async function submitData() {
    try {
        state.loading = true;
        let res: any = {};
        if(state.type === 'edit') {
            res = await update(state.formData);
        }else {
            res = await add(state.formData);
        }
        state.loading = false;
        if(res.code !== 200) return;
        notify('操作成功！', {type: 'success'});
        //关闭窗口
        close();
        //触发父组件重新加载数据
        emit('refresh');
    } catch (error) {
    } finally {
        state.loading = false;
    }
}

// 菜单类型改变
watch(() => state.formData.menuType, (val) => {
  state.formData.parentId = ''
});

function changeIsLink(val: boolean) {
  //@ts-ignore
    if(!val) state.formData.meta.linkTo = '';
}
</script>

<template>
    <el-drawer :title="title+'菜单'"  v-model="visible" :before-close="close" direction="rtl" size="650px">
        <el-form v-loading="loading" ref="formRef" :model="formData" label-width="85px" label-position="right" status-icon label-suffix=":">
            <el-form-item label="上级菜单" prop="parentId"  v-if="formData.menuType != 'M'" :rules="{required: true,message:'请选择上级菜单',trigger:'blur'}">
                <!--级联选择器-->
                <el-cascader v-model="formData.parentId"
                :options="menuList"
                :props="{checkStrictly: true, emitPath: false, value: 'menuId', label: 'menuName'}"
                clearable
                class="w100"/>
            </el-form-item>
            <el-form-item label="菜单类型" prop="menuType" :rules="{required: true,message:'请输入菜单类型',trigger:'blur'}">
                <el-radio v-model="formData.menuType" label="M" border>父菜单</el-radio>
                <el-radio v-model="formData.menuType" label="C" border>菜单</el-radio>
                <el-radio v-model="formData.menuType" label="F" border>按钮</el-radio>
            </el-form-item>
            <el-form-item label="菜单名称" prop="menuName" :rules="{required: true,message:'请输入菜单名称',trigger:'blur'}">
                <el-input v-model="formData.menuName" placeholder="请输入菜单名称" maxlength="50" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="权限标识" prop="perms">
                <el-input v-model="formData.perms" placeholder="请输入权限标识" maxlength="50" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="路由地址" prop="path">
                    <el-input v-model="formData.path" placeholder="请输入路由地址path值" maxlength="200" show-word-limit></el-input>
                </el-form-item>
            <template v-if="formData.menuType == 'C'">
                <el-form-item label="路由名称" prop="pathName">
                    <el-input v-model="formData.pathName" placeholder="请输入路由名称相对路径" maxlength="399" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="菜单图标" prop="icon">
                    <el-input v-model="formData.icon" placeholder="请输入图标名 ele- 开头" maxlength="100" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="组件路径" prop="component">
                    <el-input v-model="formData.component" placeholder="请输入组件路径地址redirect值" maxlength="200" show-word-limit></el-input>
                </el-form-item>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="是否外链" prop="isFrame">
                            <el-radio-group v-model="formData.isFrame" @change="changeIsLink">
                                <el-radio value="1">否</el-radio>
                                <el-radio value="0">是</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="16" v-if="formData.isLink">
                        <el-form-item label="外链地址" prop="linkTo">
                            <el-input v-model="formData.linkTo" placeholder="请输入外链地址" maxlength="300" show-word-limit></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="是否隐藏" prop="isHidden" :rules="{required: true,message:'是否隐藏为必选项',trigger:'change'}">
                            <el-radio-group v-model="formData.isHidden">
                                <el-radio value="0">不隐藏</el-radio>
                                <el-radio value="1">隐藏</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="是否缓存" prop="isCache" :rules="{required: true,message:'是否缓存为必选项',trigger:'change'}">
                            <el-radio-group v-model="formData.isCache">
                                <el-radio value="0">不缓存</el-radio>
                                <el-radio value="1">缓存</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="显示导航" prop="meta.isBreadcrumd">
                    <el-radio-group v-model="formData.meta.isBreadcrumd">
                        <el-radio :value="false">不显示</el-radio>
                        <el-radio :value="true">显示</el-radio>
                    </el-radio-group>
                </el-form-item>
            </template>
            <el-form-item label="排序号" prop="orderNum" :rules="{required: true,message:'请输入排序号',trigger:'blur'}">
                <el-input-number v-model="formData.orderNum" :min="1" :max="10000" style="width: 300px"/>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注信息" maxlength="50" show-word-limit/>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-row justify="center">
                <el-button @click="close">取消</el-button>
                <el-button :loading="loading" @click="submitForm" type="primary">保存</el-button>
            </el-row>
        </template>
    </el-drawer>
</template>

<style scoped>

</style>
